package com.hxzy.service.impl.token;

import cn.hutool.core.date.DateUtil;
import cn.hutool.jwt.JWTUtil;
import com.hxzy.common.constants.MarketConstants;
import com.hxzy.common.constants.RedisConstants;
import com.hxzy.common.util.MarketThreadLocalUtil;
import com.hxzy.controller.admin.login.resp.AdminLoginResp;
import com.hxzy.service.TokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * 管理员和商家令牌管理业务逻辑
 */
@Service
public class AdminTokenService implements TokenService<AdminLoginResp> {

    @Autowired
    private RedisTemplate  redisTemplate;

    /**
     * 创建令牌
     * @param entity
     * @return
     */
    @Override
    public String createToken(AdminLoginResp entity) {
        //生成唯一标识
        entity.setUuid(entity.getPermissions()+"-"+UUID.randomUUID().toString());
        //生成一个过期时间
        entity.setExpired(DateUtil.offsetMinute(new Date(), (int) TokenService.ADMIN_TOKEN_EXPIRED_MINUTES));

        this.refreshToken(entity);

        //使用jwt来对 uuid再一次的加密
        Map<String,Object> dataMap=new HashMap<>();
        dataMap.put("uuid", entity.getUuid());


        return JWTUtil.createToken(dataMap, TokenService.ADMIN_SINGATURE.getBytes());
    }

    /**
     * 把数据存储到redis中
     * @param entity 登录信息
     */
    @Override
    public void refreshToken(AdminLoginResp entity) {
        String redisKey= RedisConstants.ACCOUNT_TOKEN_PREFIX +   entity.getUuid();
        this.redisTemplate.opsForValue().set(redisKey,entity, TokenService.ADMIN_TOKEN_EXPIRED_MINUTES, TimeUnit.MINUTES);
    }

    /**
     * 根据jwt令牌从redis中获取用户身份信息
     * @param jwtToken
     * @return
     */
    @Override
    public AdminLoginResp getLoginResp(String jwtToken) {
        //1、判断jwtToken字符串是不是有额外标识 'Bearer 令牌'
        //jwtToken="Bearer eyJhbGciOiJIUzUxMiJ9.eyJsb2dpbl91c2VyX2tleSI6IjU3ODZlYzY5LWZjYTMtNDJjOS1iNmRjLTZmOWJiODkyNWU5MSJ9.DfAhxyXioZ1sXfmBNwIYSPonw6gck0hSd4wkWSbRfQnyim4jS6AWX43WwPMHqLHKz7GPX3C9pM_IMm-GjIbK1"
        if(jwtToken.startsWith(MarketConstants.ADMIN_TOKEN_PREFIX)){
            jwtToken=jwtToken.replace(MarketConstants.ADMIN_TOKEN_PREFIX,"").trim();
        }

        //2、判断jwt是否正确的
        if(!JWTUtil.verify(jwtToken, TokenService.ADMIN_SINGATURE.getBytes())){
            return null;
        }

        //3、解析jwt的值  商户类型-31b8624d-7d80-4b0b-8172-5db4f9770b4d
        Object uuid = JWTUtil.parseToken(jwtToken).getPayload("uuid");

        //4、拼接rediskey account:token:admin-a99bf377-c520-4028-ae1b-fd2f2a43347b
         String redisKey= RedisConstants.ACCOUNT_TOKEN_PREFIX +uuid;

        Object redisValue = this.redisTemplate.opsForValue().get(redisKey);

        return Objects.isNull(redisValue)? null: (AdminLoginResp) redisValue;
    }

    @Override
    public void logout() {
        AdminLoginResp adminLoginResp = MarketThreadLocalUtil.ADMIN_THREAD_LOCAL.get();
        String redisKey= RedisConstants.ACCOUNT_TOKEN_PREFIX+adminLoginResp.getUuid();
        this.redisTemplate.delete(redisKey);
    }
}
